﻿//***********************************************************************
// Assembly         : phpmk
// Author           : 
// Created          : 04-12-2010
//
// Last Modified By : 
// Last Modified On : 04-12-2010
// Description      : 
//
// Copyright        : (c) Another-D-Mention Software. All rights reserved.
//***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using phpmk.ADM.Utils;
using phpmk.ADM.Out;
using System.Windows.Forms;
using System.Xml;
using phpmk.ADM.Core;

namespace phpmk.ADM.Commands.Update {
    class UpdateCommand : ICommand {

        private StringDictionary arguments;

        public void Execute(StringDictionary args) {
            this.arguments = args;
            Output output = Output.GetInstance();
           
            output.TimeStamp = false;
            output.Write("Getting version information...");

            try {
                String result = WebUtil.PostToUrl(Constants.UpdateUrl, "app=" + Application.ProductName +"&version=" + Application.ProductVersion, 3000);                
                output.SetStatus(ActionStatus.OK);
                XmlDocument xmlDoc = new XmlDocument();
                try {
                    xmlDoc.LoadXml(result);

                    if (xmlDoc.GetElementsByTagName("status")[0].InnerText == "No new version available") {
                        output.Info("You have the latest version");
                    } else {
                        output.Info("New version available to download: " + xmlDoc.GetElementsByTagName("version")[0].InnerText);
                        if (Util.CopyToClipboard(xmlDoc.GetElementsByTagName("download")[0].InnerText)) {
                            output.Info("Download link copied to clipboard!");
                        } else {
                            output.Write("Link: " + xmlDoc.GetElementsByTagName("download")[0].InnerText);
                        }
                    }
                } catch (XmlException ex) {
                    Debug.Log(ex.Message);
                    output.Error(ErrorMessages.FaildToParseResult);
                }

            } catch (ResponseException ex) {
                Debug.Log(ex.Message);
                output.SetStatus(ActionStatus.FAILED);
            }
        }

        public void Help()
        {
            Output output = Output.GetInstance();
            output.Info("Checks for software updates. Requires internet connection");
        }

        public string Info()
        {
            return "Checks online for a newer version of phpmk";
        }
    }
}
